﻿using AutoMapper;
using MediatR;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.DeepProcess
{
    public class DeepProcessEaditCommandHandler : IRequestHandler<DeepProcessEaditCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_DeepProcess> deepProcessRepository;
        private readonly IBaseRepository<T_Traceability> tranceRepository;
        private readonly IMapper mapper;

        public DeepProcessEaditCommandHandler(IBaseRepository<T_DeepProcess> deepProcessRepository, IMapper mapper, IBaseRepository<T_Traceability> tranceRepository)
        {
            this.deepProcessRepository = deepProcessRepository;
            this.mapper = mapper;
            this.tranceRepository = tranceRepository;
        }

        public async Task<APIResult<int>> Handle(DeepProcessEaditCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
            var deep = mapper.Map<T_DeepProcess>(request);
            var model = deepProcessRepository.GetAll().FirstOrDefault(x => x.ID == request.ID);
            if (model == null)
            {
                result.Message = "添加成功";
                result.Data = await deepProcessRepository.Add(deep);
                var data = tranceRepository.GetAll().FirstOrDefault(x => x.Batch == request.Batch);
                data.Perfection += 30;
                await tranceRepository.Update(data);
                return await Task.FromResult(result);
            }
            else 
            {
                result.Message = "修改成功";
                var deeps = mapper.Map(request, model);
                result.Data =await deepProcessRepository.Update(deeps);
                return await Task.FromResult(result);
            }
        }
    }
}
